from django import forms

from webapp.uitls.bootstrapmodelform import BootStrapModelForm, BootStrapForm
from webapp.models import UserInfo, Mobile, Admin
import re
from django.core.exceptions import ValidationError


class LoginForm(BootStrapForm):
    username = forms.CharField(max_length=32, label='用户名', widget=forms.TextInput)
    password = forms.CharField(max_length=64, label='密码', widget=forms.PasswordInput)
    captcha = forms.CharField(max_length=64, label='验证码', widget=forms.TextInput)


class UserInfoModelForm(BootStrapModelForm):
    # 重写字段，添加额外的校验条件
    password = forms.CharField(min_length=6, label="密码")

    # 编写内部类Meta
    class Meta:
        model = UserInfo
        fields = ["name", "password", "age", "account", "gender", "depart", "create_time"]
        # 原始方法添加样式，需每个字段逐一调整
        # widgets = {
        #     "name": forms.TextInput(attrs={"class":"form-control", "style":"width: 20%"})
        # }


class MobileModelForm(BootStrapModelForm):
    # 重写字段，添加校验规则（方法一）
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator("[0-9-()（）]{7,18}", "输入的手机号格式不正确")]
    # )

    # 使用钩子方法，添加校验规则（方法二）
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        exists = Mobile.objects.filter(mobile=txt_mobile).exists()

        if re.match(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$',
                    txt_mobile):
            if exists:
                raise ValidationError("手机号已存在")
            return txt_mobile
        raise ValidationError("手机号格式异常")

    class Meta:
        model = Mobile
        fields = ["mobile", "level", "price", "status"]


class MobileEdModelForm(BootStrapModelForm):
    # 重写字段，添加校验规则（方法一）
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator("[0-9-()（）]{7,18}", "输入的手机号格式不正确")]
    # )

    # 使用钩子方法，添加校验规则（方法二）
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        exists = Mobile.objects.filter(mobile=txt_mobile).exclude(id=self.instance.pk).exists()
        print(self.instance.pk)
        print(exists)
        if re.match(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$',
                    txt_mobile):
            if exists:
                raise ValidationError("手机号已存在")
            return txt_mobile
        raise ValidationError("手机号格式异常")

    class Meta:
        model = Mobile
        fields = ["mobile", "level", "price", "status"]


class AdminModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(label="确认密码", max_length=64)

    class Meta:
        model = Admin
        fields = ["username", "password", "confirm_password"]

    def clean_confirm_password(self):
        confirm_password = self.cleaned_data["confirm_password"]
        password = self.cleaned_data["password"]
        if password != confirm_password:
            raise ValidationError("密码不一致")
        return confirm_password
